<?php

namespace app\job;

use app\admin\model\Scenic;
use ba\ScenicApi;
use think\facade\Log;
use think\queue\Job;

class AddScenic
{
    public static string $queue = 'add_scenic';

    public function fire(Job $job, $data)
    {
        $scenicApi = (new ScenicApi());
        $scenicModel = new Scenic();
        Log::info('开始执行队列，队列信息：' . json_encode($data, JSON_UNESCAPED_UNICODE));
        try {
            foreach ($data as $val) {
                //查询是否存在，存在则跳出
                $count = $scenicModel->where(['scenic_id' => $val['scenicId']])->count();
                if($count) continue;
                $res = $scenicApi->getDetail($val['scenicId']);
                $addressLatLng = isset($val['blocation']) ? explode(',', $val['blocation']) : '';
                $arr = [
                    'scenic_id' => $val['scenicId'],
                    'name' => $val['scenicName'] ?? '',
                    'cover' => $val['newPicUrl'] ?? '',
                    'banner' => $res['defaultPic'] ?? '',
                    'address' => $res['scenicAddress'] ?? '',
                    'openTime' => $val['bizTime'] ?? '',
                    'city_name' => $res['cityName'] ?? '',
                    'traffic_bus' => $res['trafficBus'] ?? '',
                    'scenic_des' => $res['scenicDescription'],
                    'book_notice' => $res['bookNotice'][4]['value'] ?? '',
                    'latitude' => $addressLatLng[0] ?? '',
                    'longitude' => $addressLatLng[1] ?? '',
                    'create_time' => time(),
                    'status' => 0
                ];
                $scenicModel->insert($arr);
            }
            $job->delete();
        } catch (\Exception $e) {
            // 任务失败时的处理，允许重试
            Log::info('队列错误信息：' . $e->getMessage());
            $job->release(30); // 30秒后重试
        }
    }
}
